<template>
  <el-dialog @close="close" title="图片裁剪" v-model="isVisible" append-to-body>
    <div class="image-cropper">
      <img :src="baseImageUrl" id="processed-image" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="cropperHandler()">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, watch, nextTick } from "vue";
import Cropper from "cropperjs";
import { uploadApi } from "@/api/common.api";
export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    ratio: {
      // 比例
      type: Number,
    },
    baseImageUrl: {
      type: String,
      required: true,
    },
  },
  setup(props, context) {
    let isVisible = ref(false);
    let cropper: Cropper;
    let cropperHandler = () => {
      cropper.getCroppedCanvas().toBlob(async (blob) => {
        if (blob) {
          const formData = new FormData();
          formData.append("file", blob, "file.png");
          let res: any = await uploadApi(formData);
          context.emit("onChangeFile", res.urls[0]);
          close();
        }
      });
    };

    let close = () => {
      context.emit("update:modelValue", false);
    };

    watch(
      () => props.modelValue,
      async (newVal: boolean) => {
        isVisible.value = newVal;
        if (newVal) {
          await nextTick();
          const image = document.getElementById("processed-image") as HTMLImageElement;
          image.crossOrigin = "anonymous";
          cropper = new Cropper(image, {
            checkCrossOrigin: false,
            crop(event) {
              const { x, y, width, height } = event.detail;
              console.log(x, y, width, height);
            },
            ...(props.ratio && { aspectRatio: props.ratio }),
          });
        } else {
          if (cropper) {
            cropper.destroy();
          }
        }
      }
    );

    return {
      isVisible,
      cropperHandler,
      close,
    };
  },
});
</script>

<style lang="scss" scoped>
.image-cropper img {
  display: block;
  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>
